import csv
import os
import sys

money_csv='17班费.csv'
check_dir='.check'
queue_num=1000
# text color
fg_color={
    'black': b'\033[30m',     
    'red': b'\033[31m',       
    'green': b'\033[32m',     
    'yellow': b'\033[33m',    
    'blue': b'\033[34m',      
    'magenta': b'\033[35m',   
    'cyan': b'\033[36m',      
    'white':b'\033[37m',      
}

def raw_print(s,color=None):
    if color==None:
        os.write(1,bytes(s,'utf-8'))
    else:
        os.write(1,fg_color[color]+bytes(s,'utf-8')+b'\033[0m')

def error_print(s):
    raw_print(s,'red')

def warn_print(s):
    raw_print(s,'blue')
    
def main_help():
    print('help')
    print('打印任务帮助信息，在不同任务模式下有各自的help')
    print('init')
    print('根据班级名单初始化班费.csv数据信息，只需要执行一次')
    print('spend')
    print('进行收班费和消费班费操作。如果是收班费操作，输入金额为正，消费输入为负数')
    print('back')
    print('回退版本')
    print('go')
    print('前进版本')
    print('quit')
    print('退出')
    print('print')
    print('打印班费信息')
	
def main_init():
    class_csv='17级种子班名单.csv'
    if not os.path.isfile(class_csv):
        error_print('名单不存在')
        return
    
    global money_csv
    
    if os.path.isfile(money_csv):
        warn_print('已经存在17班费.csv文件，是否覆盖？（y/n）')
        y=input().lstrip().rstrip()
        if not y=='y':
            return
    with open(class_csv,'r') as f:
        class_list=[[i for i in j.split(',')] for j in f.read().split('\n')]
    money_list=[]
    money_list.append(class_list[0][:2]+['个人余'])
    for i in class_list[1:]:
        if i[0]=='':
            break
        money_list.append(i[:2]+['0'])
    money_list.append(['','','总缴纳'])
    money_list.append(['','','总人数'])
    money_list.append(['','','总余额'])
    money_list.append(['','','备注'])
    with open(money_csv,'w+') as f:
        money_s='\n'.join([','.join(i) for i in money_list])
        f.write(money_s)

def get_num_str(l):
    num_str=''
    for i,j in enumerate(l[1:]):
        if j[0]=='':
            break
        num_str+=str(j[:2])
        num_str+='\t'
        if i%3==2:
            num_str+='\n'
    return num_str

def main_spend():
    global money_csv
    if not os.path.isfile(money_csv):
        error_print(money_csv+'不存在,请先init')
        return
    print('输入消费总金额')
    with open(money_csv,'r') as f:
        money_list=[[i for i in j.split(',')] for j in f.read().split('\n')]
        
    money=float(input().lstrip().rstrip())
    print(get_num_str(money_list))
    print('请依次输入消费的学号，通过空隔分隔,结尾是n代表取反')
    s=input()
    print('请输入备注')
    mark=input()
    num_list=[i for i in s.split(' ') if not i=='']
    
    neg=False
    if num_list[-1]=='n':
        neg=True
    if not neg:
        people_num=len(num_list)
    else:
        people_num=len(money_list)-5-len(num_list)+1
    one_money=money/people_num
    xor_sum=0
    for i in money_list[1:-4]:
        if i=='n':
            continue
        if (i[0] in num_list) == (not neg):
            i.append(str(one_money))
            #算个人总金
            i[2]=str(float(i[2])+one_money)
        else:
            i.append(str(0.0))
        
    #提交的纪录
    if len(money_list[0])==3:
        money_list[0].append(str(1))
    else:
        money_list[0].append(str(int(money_list[0][-1])+1))
        
    #班费总缴纳额
    money_list[-4].append(str(money))
    #交班费总人数
    money_list[-3].append(str(people_num))
    #班费余额
    if(len(money_list[-2])==3):
        money_list[-2].append(str(money))
    else:
        money_list[-2].append(str(float(money_list[-2][-1])+money))
        
    money_list[-1].append(mark)
    
    with open(money_csv,'w+') as f:
        f.write('\n'.join([','.join(i) for i in money_list]))

def main_print():
    if not os.path.isfile(money_csv):
        error_print(money_csv+'不存在')
        return
    with open(money_csv,'r') as f:
        print(f.read().replace(',','\t'))

def main_check():
    if not os.path.isfile(money_csv):
        return
    if not os.path.exists(check_dir):
        os.mkdir(check_dir)
        with open(check_dir+'/.queue','w+') as f:
            #标记下一次写的文件位置
            f.write('1')
    with open(check_dir+'/.queue','r') as f:
        this_num=int(f.read())
    with open('17班费.csv','r') as f:
        with open(check_dir+'/'+str(this_num),'w+') as f1:
            f1.write(f.read())
            
    with open(check_dir+'/.queue','w+') as f:
        f.write(str((this_num+1)%queue_num))

def main_back(is_back):
    if (not os.path.exists(check_dir)) or (not os.path.isfile(check_dir+'/1')) or (not os.path.isfile(check_dir+'/.queue')):
        error_print('没有检查文件夹或者检查点\n')
        return
    with open(check_dir+'/.queue','r') as f:
        this_num=int(f.read())
    if is_back:
        last_num=(this_num-1)%queue_num
    else:
        last_num=(this_num+1)%queue_num
    if not os.path.isfile(check_dir+'/'+str(last_num)):
        error_print('没有更多的检查点（回退或者前进）\n')
        return
    #备份这次
    if is_back:
        with open(money_csv,'r') as f:
            with open(check_dir+'/'+str(this_num),'w+') as f1:
                f1.write(f.read())
    #回退
    with open(money_csv,'w+') as f:
        with open(check_dir+'/'+str(last_num),'r') as f1:
            f.write(f1.read())
    with open(check_dir+'/.queue','w+') as f:
        f.write(str(last_num))
        
def main_loop():
    print('请输入想要处理的任务，输入help显示帮助')
    raw_print('>>')
    s=input().lstrip().rstrip()
    if s=='help':
        main_help()
    elif s=='init':
        main_check()
        main_init()
    elif s=='spend':
        main_check()
        main_spend()
    elif s=='print':
        main_print()
    elif s=='back':
        main_back(True)
    elif s=='go':
        main_back(False)
    elif s=='quit':
        return
    else:
        check=False
        print('命令输入类型错误，重新输入')

def main():
    while True:
        main_loop()


if __name__=='__main__':
    main()
